package net.sk.web;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import net.sk.pt.IConsumer;
import net.sk.pt.IFilter;
import net.sk.pt.IKeeper;
import net.sk.pt.IProvider;
import net.sk.pt.State;

public class Provider implements IProvider {
	private Object key;
	private IKeeper keeper;
	private HashMap<Object,IConsumer> consumers;
	private HashMap<Object,IFilter> filters;

	public Provider(IKeeper kp,Object key){
		init(kp,key);
	}
	@Override
	public Object getKey() {
		// TODO Auto-generated method stub
		return key;
	}

	@Override
	public void send(State s) {
		// TODO Auto-generated method stub
		keeper.update(s);
		Iterator<Entry<Object,IConsumer>> iter = consumers.entrySet().iterator(); 
		while (iter.hasNext()) { 
			Entry<Object,IConsumer> entry = iter.next(); 
			IConsumer cur = entry.getValue(); 
			IFilter fl = filters.get(entry.getKey());
			if(fl==null || fl.bSend(s)){
				boolean bsucc = cur.send(this,s);
				//发送失败,不再重发
				if(!bsucc){
					consumers.remove(entry.getKey());
				}
			}
		} 	
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		consumers.clear();
		filters.clear();	
		keeper.destory();
	}

	@Override
	public void init(IKeeper kp,Object key) {
		// TODO Auto-generated method stub
		this.keeper = kp;
		this.key = key;
		consumers = new HashMap<Object,IConsumer>();
		filters = new HashMap<Object,IFilter>();
	}

	@Override
	public void removeConsumer(IConsumer cs) {
		// TODO Auto-generated method stub
		Object key_cs = cs.getKey();
		consumers.remove(key_cs);
		filters.remove(key_cs);
		//cs.destory();
	}

	@Override
	public void addConsumer(IConsumer cs, IFilter fl) {
		// TODO Auto-generated method stub
		Object key_cs = cs.getKey();
		consumers.put(key_cs, cs);
		if(fl!=null)
			filters.put(key_cs, fl);
		//根据订阅条件发送当前状态
		List<State> states = keeper.getStateByFilter(fl);
		int len = states.size();
		for(int i=0; i<len; i++){
			cs.send(this,states.get(i));
		}
		//发送结束标志
		cs.send(this,StateCenter.getStateEnd());
		states.clear();
	}
	@Override
	public IKeeper getKeeper() {
		// TODO Auto-generated method stub
		return this.keeper;
	}
	@Override
	public HashMap<Object, IConsumer> getConsumers() {
		// TODO Auto-generated method stub
		return consumers;
	}

}
